package com.ruoyi.web.controller.applet;

import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.entity.TUser;
import com.ruoyi.common.entity.TUserRealAuth;
import com.ruoyi.common.service.ITUserRealAuthService;
import com.ruoyi.common.service.ITUserService;
import com.ruoyi.common.utils.CommonUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.TokenUtils;
import com.ruoyi.common.utils.WeChatUtil;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.vo.WeChatVO;
import com.ruoyi.framework.config.ServerConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 用户Controller
 *
 * @author ruoyi
 * @date 2024-06-02
 */
@RestController
@RequestMapping("/applet/user")
public class TUserController extends BaseController
{
    @Autowired
    private ITUserService tUserService;
    @Autowired
    private WeChatUtil weChatUtil;
    @Autowired
    private ITUserRealAuthService realAuthService;
    @Autowired
    private ServerConfig serverConfig;

    /**
     * 用户登录
     * @param code
     * @param request
     * @return
     */
    @GetMapping("/login")
    public AjaxResult login(String code, HttpServletRequest request){
        WeChatVO weChatInfo = weChatUtil.getWeChatInfo(code);
        System.out.println("用户登录code==="+code);
        System.out.println(weChatInfo);
        if(StringUtils.isEmpty(weChatInfo.getOpenid())){
            return AjaxResult.error("登录失败，请稍后重试");
        }
        TUser tUser = tUserService.selectTUserByUnionId(weChatInfo.getUnionid());
        Long id = 0L;
        if(null == tUser){
            //执行数据写入
            TUser member = new TUser();
            member.setOpenid(weChatInfo.getOpenid());
            member.setUnionId(weChatInfo.getUnionid());
            tUserService.insertTUser(member);
            id = member.getId();
        }else{
            id = tUser.getId();
        }
        System.out.println("最终用户id======"+id);
        String s = TokenUtils.setToken(Integer.parseInt(id+""));
        Map<String,String> map = new HashMap<>();
        map.put("token",s);
        return AjaxResult.success(map);
    }

    /**
     * 获取登录用户手机号
     * @param code
     * @param request
     * @return
     * @throws Exception
     */
    @GetMapping("/getUserMobile")
    public AjaxResult getUserMobile(String code,HttpServletRequest request) throws Exception {
        System.out.println("获取手机号code==="+code);
        Long userId = CommonUtils.getUserId(request);
        if(StringUtils.isEmpty(code)){
            return AjaxResult.error("获取手机号失败");
        }
        try {
            String userPhoneNumber = weChatUtil.getUserPhoneNumber(code);
            TUser member = new TUser();
            member.setId(userId);
            member.setPhone(userPhoneNumber);
            tUserService.updateTUser(member);
            Map<String,String> map = new HashMap<>();
            map.put("mobile",userPhoneNumber);
            return AjaxResult.success(map);
        }catch (Exception e){
            return AjaxResult.error("获取手机号失败");
        }
    }

    /**
     * 获取用户信息
     * @param request
     * @return
     */
    @GetMapping("/getUserInfo")
    public AjaxResult getUserInfo(HttpServletRequest request) throws Exception {
        Long userId = CommonUtils.getUserId(request);
        System.out.println("获取到的用户id=="+userId);
        TUser member = tUserService.selectTUserById(userId);
        Map<String,Object> map = new HashMap<>();
        map.put("id",member.getId());
        map.put("name",member.getName());
        map.put("mobile",member.getPhone());
        map.put("openid",member.getOpenid());
        map.put("headImg",member.getAvatar());
        map.put("createTime",member.getCreateTime());
        return AjaxResult.success(map);
    }

    /**
     * 修改用户信息
     * @param request
     * @return
     */
    @PutMapping("/setUserInfo")
    public AjaxResult setUserInfo(@RequestBody TUser user, HttpServletRequest request) throws Exception {
        Long userId = CommonUtils.getUserId(request);
        user.setId(userId);
        tUserService.updateTUser(user);
        return AjaxResult.success();
    }

    /**
     * 通用上传请求（单个）
     */
    @PostMapping("/upload")
    public AjaxResult uploadFile(MultipartFile file, HttpServletRequest request) throws Exception
    {
        try
        {
            String clientUrl = "https://5.6fh.top";
            CommonUtils.getUserId(request);
            // 上传文件路径
            String filePath = RuoYiConfig.getUploadPath();
            // 上传并返回新文件名称
            String fileName = FileUploadUtils.upload(filePath, file);
            String url = clientUrl + fileName;
            AjaxResult ajax = AjaxResult.success();
            ajax.put("url", url);
            ajax.put("fileName", fileName);
            ajax.put("newFileName", FileUtils.getName(fileName));
            ajax.put("originalFilename", file.getOriginalFilename());
            Map<String,String> map = new HashMap<>();
            map.put("url",url);
            return AjaxResult.success(map);
        }
        catch (Exception e)
        {
            return AjaxResult.error(e.getMessage());
        }
    }

    /**
     * 实名提交
     * @param request
     * @return
     */
    @PostMapping("/realAuthSubmit")
    public AjaxResult realAuthSubmit(@RequestBody TUserRealAuth user, HttpServletRequest request) throws Exception {
        Long userId = CommonUtils.getUserId(request);
        if(null == user.getId()) {
            TUserRealAuth tUserRealAuth = realAuthService.selectTUserRealAuthByUserId(userId);
            user.setUserId(userId);
            if(null == tUserRealAuth) {
                realAuthService.insertTUserRealAuth(user);
            }else{
                user.setId(tUserRealAuth.getId());
                realAuthService.updateTUserRealAuth(user);
            }
        }else{
            realAuthService.updateTUserRealAuth(user);
        }
        return AjaxResult.success();
    }
}
